package com.neusoft.crm.tasks;

import com.neusoft.crm.po.ClientInfo;
import com.neusoft.crm.po.Orders;
import com.neusoft.crm.po.SysUser;
import com.neusoft.crm.service.IClientInfoService;
import com.neusoft.crm.service.ISysUserService;
import com.neusoft.crm.utils.EncryptorUtil;
import com.neusoft.crm.utils.GetDataStr;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * xxl计划任务类
 *
 * @author msprc
 */
@Slf4j
@Component
public class XxlJobTest {

    @Autowired
    private IClientInfoService clientInfoService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 根据计划任务自动更新数据库中客户状态
     *
     * @return 执行结果
     */
    @XxlJob("checkClientInfo")
    public ReturnT<String> checkClientInfo() {
        String todayDate = GetDataStr.getDataStr();
        String returnStr;
        // 获取当前用户参数，同时做鉴权
        String param = XxlJobHelper.getJobParam();
        String[] methodParams = param.split(";");
        EncryptorUtil encryptor = new EncryptorUtil();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(methodParams[0]);
        sysUser.setUserPassword(encryptor.getSha256(methodParams[1]));
        if (sysUserService.selectSysUserByNameByPass(sysUser) == null) {
            // 未通过鉴权，执行结果为失败
            ReturnT<String> fail = ReturnT.FAIL;
            returnStr = "---------" + todayDate + "客户状态检查失败：原因为鉴权失败（账号或密码错误）--------";
            log.info(returnStr);
            XxlJobHelper.handleFail(returnStr);
            return fail;
        }
        //鉴权通过，开始执行
        int updateCount = 0;
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setClientState(1);
        List<ClientInfo> clientInfoList = clientInfoService.showClientInfoList(clientInfo);
        for (ClientInfo c : clientInfoList) {
            List<Orders> orders = clientInfoService.selectOrdersByclientCode(c);
            if (orders.size() > 0) {
                if (isIntervalGreaterThan180Days(orders.get(orders.size() - 1).getOrdersDate(), todayDate)) {
                    c.setClientState(2);
                    if (clientInfoService.updateClientStatus(c) == 1) {
                        updateCount++;
                    } else {
                        log.error("更新失败，对象为：" + c.getClientCode());
                    }
                }
            }
        }
        //执行结果为成功
        ReturnT<String> success = ReturnT.SUCCESS;
        returnStr = "---------" + todayDate + "：客户状态检查成功，共更新：" + updateCount + "条记录--------";
        log.info(returnStr);
        //执行结束，返回给调度器的数据
        XxlJobHelper.handleSuccess(returnStr);
        return success;

    }

    /**
     * 每天0点初始化当日的客户id索引
     *
     * @return 执行结果
     */
    @XxlJob("initClientCode")
    public ReturnT<String> initClientCode() {
        GetDataStr.initClientIndex();
        //执行结果为成功
        ReturnT<String> success = ReturnT.SUCCESS;
        String returnStr = "---------" + GetDataStr.getDataStr() + "：客户id索引重置成功--------";
        log.info(returnStr);
        //执行结束，返回给调度器的数据
        XxlJobHelper.handleSuccess(returnStr);
        return success;
    }

    /**
     * 判断两个日期间隔是否大于180天
     *
     * @param date1 要检查的日期
     * @param date2 当前日期
     * @return 是否大于
     */
    private boolean isIntervalGreaterThan180Days(String date1, String date2) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串解析为LocalDate对象
        LocalDate localDate1 = LocalDate.parse(date1, formatter);
        LocalDate localDate2 = LocalDate.parse(date2, formatter);
        // 计算两个日期的间隔天数
        long days = Math.abs(localDate1.toEpochDay() - localDate2.toEpochDay());
        // 判断间隔天数是否大于180天
        return days > 180;
    }


}